#!/usr/bin/env python
# -*- coding: utf-8 -*-

# pip install flask
# pip install flask-restful
# pip install flask-httpauth
# pip install itsdangerous

# ==========  ===============================================  =============================
# HTTP 方法   URL                                              动作
# ==========  ===============================================  ==============================
# GET         http://[hostname]/api/v1.0/tasks            检索任务列表
# GET         http://[hostname]/api/v1.0/tasks/[task_id]  检索某个任务
# POST        http://[hostname]/api/v1.0/tasks            创建新任务
# PUT         http://[hostname]/api/v1.0/tasks/[task_id]  更新任务
# DELETE      http://[hostname]/api/v1.0/tasks/[task_id]  删除任务
# ==========  ================================================ =============================

# 不用校验是否登录的例子：curl -i http://localhost:5000/api/v1.0/cities
# 需要校验是否登录的例子：curl -u admin:admin -i http://localhost:5000/api/v1.0/orders

from flask import Flask, g, make_response, jsonify
from flask_restful import Api
from flask_cors import CORS
from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired)
from common import erppeek
from common import odooClient
from common.auth import Auth

from resource.banner import BannerListAPI
from resource.notice import NoticeListAPI
from resource.city import ResCityListAPI, ResCityAPI
from resource.product import ProductProductListAPI, ProductProductAPI
from resource.user import ResUsersAPI
from resource.order import SaleOrderListAPI

app = Flask(__name__)
app.config['SECRET_KEY'] = 'ShiGuang@2017'
api = Api(app)
CORS(app, supports_credentials=True)
basic_auth, token_auth, multi_auth = Auth.getInstance()

@basic_auth.verify_password
def verify_password(username_or_token, password):
    try:
        if not verify_token(username_or_token):
            g.odoo = erppeek.Client(odooClient.ODOO_HOST, odooClient.ODOO_DB, username_or_token, password)
            g.username = username_or_token
            g.password = password
            return True
        else:
            return True
    except:
        return False

@app.route('/api/v1.0/token')
@basic_auth.login_required
def get_auth_token():
    serializer = Serializer(app.config['SECRET_KEY'], expires_in=600)
    token = serializer.dumps({'username': g.username, 'password': g.password})
    return jsonify({'token': token.decode('ascii')})

@token_auth.verify_token
def verify_token(token):
    g.username = None
    serializer = Serializer(app.config['SECRET_KEY'])
    try:
        data = serializer.loads(token)
    except SignatureExpired:
        return False  # valid token, but expired
    except BadSignature:
        return False  # invalid token
    if 'username' in data:
        g.username = data['username']
        return True
    return False

@token_auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 401)

@app.route('/')
@multi_auth.login_required
def index():
    return "Hello, %s!" % g.username

# 绑定资源和路由
api.add_resource(BannerListAPI, '/api/v1.0/banners')
api.add_resource(NoticeListAPI, '/api/v1.0/notices')
api.add_resource(ResCityListAPI, '/api/v1.0/cities')
api.add_resource(ResCityAPI, '/api/v1.0/cities/<int:city_id>')
api.add_resource(ProductProductListAPI, '/api/v1.0/products')
api.add_resource(ProductProductAPI, '/api/v1.0/products/<int:product_id>')
api.add_resource(ResUsersAPI, '/api/v1.0/user')
api.add_resource(SaleOrderListAPI, '/api/v1.0/orders')

if __name__ == '__main__':
    app.run(debug=True)
    # app.run(host='0.0.0.0')
